﻿// This software is the confidential and proprietary information of NetBay.
// Such confidential information should not be disclosed.
// NetBay copyright(c) 2012

#region

using System;
using System.Security;
using System.Security.Cryptography;

#endregion

namespace NetBay.Core.Encryption.Licensing
{
    /// <summary>
    /// handles license authorization.
    /// </summary>
    public abstract  class LicenseAuthorizationBase
    {
        #region Class Methods

        /// <summary>
        /// validates the license and if the app should run; if the license is valid the
        /// method will complete, if not it will throw a security exception.
        /// </summary>
        /// <param name="licenseFile">The license file.</param>
        /// <returns></returns>
        /// <exception cref="SecurityException">thrown if the license is invalid or expired</exception>
        public abstract LicenseTerms ValidateLicense(string licenseFile);

        /// <summary>
        /// generate a new, private key. this will be the master key for generating license files.
        /// </summary>
        /// <returns></returns>
        internal static String GeneratePrivateKey()
        {
            DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
            return dsa.ToXmlString(true);
        }

        /// <summary>
        /// validate license file and return the license terms.
        /// </summary>
        /// <param name="license"></param>
        /// <param name="publicKey"></param>
        /// <returns></returns>
        public static LicenseTerms GetValidTerms(LicenseFile license, String publicKey)
        {
            // create the crypto-service provider:
            DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();

            // setup the provider from the public key:
            dsa.FromXmlString(publicKey);

            // get the license terms data:
            byte[] terms = Convert.FromBase64String(license.LicenseTerms);

            // get the signature data:
            byte[] signature = Convert.FromBase64String(license.Signature);

            // verify that the license-terms match the signature data
            if (dsa.VerifyData(terms, signature))
                return LicenseTerms.FromString(license.LicenseTerms);
            else
                throw new SecurityException("Signature Not Verified!");
        }

        #endregion
    }
}